package com.imut.lagain.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imut.lagain.common.Result;
import com.imut.lagain.entity.Message;
import com.imut.lagain.service.MessageService;
import com.imut.lagain.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 消息控制器
 */
@RestController
@RequestMapping("/messages")
public class MessageController {
    private static final Logger log = LoggerFactory.getLogger(MessageController.class);
    
    @Autowired
    private MessageService messageService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 发送文本消息
     */
    @PostMapping("/send/text")
    public Result<Message> sendTextMessage(@RequestBody Map<String, Object> request, 
                                          HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            String content = request.get("content").toString();
            
            Message message = messageService.sendTextMessage(userId, receiverId, content);
            return Result.success(message);
        } catch (Exception e) {
            log.error("发送文本消息失败", e);
            return Result.error("发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 发送图片消息
     */
    @PostMapping("/send/image")
    public Result<Message> sendImageMessage(@RequestBody Map<String, Object> request, 
                                           HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            String imageUrl = request.get("imageUrl").toString();
            
            Message message = messageService.sendImageMessage(userId, receiverId, imageUrl);
            return Result.success(message);
        } catch (Exception e) {
            log.error("发送图片消息失败", e);
            return Result.error("发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 发送语音消息
     */
    @PostMapping("/send/audio")
    public Result<Message> sendAudioMessage(@RequestBody Map<String, Object> request, 
                                           HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            String audioUrl = request.get("audioUrl").toString();
            
            Message message = messageService.sendAudioMessage(userId, receiverId, audioUrl);
            return Result.success(message);
        } catch (Exception e) {
            log.error("发送语音消息失败", e);
            return Result.error("发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 回复消息
     */
    @PostMapping("/reply")
    public Result<Message> replyMessage(@RequestBody Map<String, Object> request, 
                                       HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            String content = request.get("content").toString();
            Long replyToId = Long.valueOf(request.get("replyToId").toString());
            String messageType = request.getOrDefault("messageType", "TEXT").toString();
            
            Message message = messageService.replyMessage(userId, receiverId, content, replyToId, messageType);
            return Result.success(message);
        } catch (Exception e) {
            log.error("回复消息失败", e);
            return Result.error("回复消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取聊天记录
     */
    @GetMapping("/chat/{partnerId}")
    public Result<IPage<Message>> getChatHistory(@PathVariable Long partnerId,
                                                @RequestParam(defaultValue = "1") int page,
                                                @RequestParam(defaultValue = "20") int size,
                                                HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            IPage<Message> messages = messageService.getChatHistory(userId, partnerId, page, size);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取聊天记录失败", e);
            return Result.error("获取聊天记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取聊天对话列表
     */
    @GetMapping("/partners")
    public Result<List<Map<String, Object>>> getChatPartners(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<Map<String, Object>> partners = messageService.getChatPartners(userId);
            return Result.success(partners);
        } catch (Exception e) {
            log.error("获取聊天对话列表失败", e);
            return Result.error("获取聊天对话列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取最新消息
     */
    @GetMapping("/latest/{partnerId}")
    public Result<Message> getLatestMessage(@PathVariable Long partnerId,
                                           HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Message message = messageService.getLatestMessage(userId, partnerId);
            return Result.success(message);
        } catch (Exception e) {
            log.error("获取最新消息失败", e);
            return Result.error("获取最新消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread/count")
    public Result<Long> getUnreadMessageCount(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long count = messageService.getUnreadMessageCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取未读消息数量失败", e);
            return Result.error("获取未读消息数量失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取与指定用户的未读消息数量
     */
    @GetMapping("/unread/count/{partnerId}")
    public Result<Long> getUnreadMessageCountBetween(@PathVariable Long partnerId,
                                                    HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long count = messageService.getUnreadMessageCountBetween(partnerId, userId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取未读消息数量失败", e);
            return Result.error("获取未读消息数量失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记消息为已读
     */
    @PutMapping("/read/{messageId}")
    public Result<Boolean> markAsRead(@PathVariable Long messageId,
                                     HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = messageService.markAsRead(messageId, userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("标记消息已读失败", e);
            return Result.error("标记消息已读失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量标记消息为已读
     */
    @PutMapping("/read/all/{partnerId}")
    public Result<Boolean> markAllAsRead(@PathVariable Long partnerId,
                                        HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = messageService.markAllAsReadBetween(partnerId, userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("批量标记消息已读失败", e);
            return Result.error("批量标记消息已读失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除消息
     */
    @DeleteMapping("/{messageId}")
    public Result<Boolean> deleteMessage(@PathVariable Long messageId,
                                        HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = messageService.deleteMessage(messageId, userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("删除消息失败", e);
            return Result.error("删除消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 撤回消息
     */
    @PutMapping("/recall/{messageId}")
    public Result<Boolean> recallMessage(@PathVariable Long messageId,
                                        HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            boolean success = messageService.recallMessage(messageId, userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("撤回消息失败", e);
            return Result.error("撤回消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 搜索消息
     */
    @GetMapping("/search/{partnerId}")
    public Result<List<Message>> searchMessages(@PathVariable Long partnerId,
                                               @RequestParam String keyword,
                                               HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<Message> messages = messageService.searchMessages(userId, partnerId, keyword);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("搜索消息失败", e);
            return Result.error("搜索消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取系统消息
     */
    @GetMapping("/system")
    public Result<IPage<Message>> getSystemMessages(@RequestParam(defaultValue = "1") int page,
                                                   @RequestParam(defaultValue = "20") int size,
                                                   HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            IPage<Message> messages = messageService.getSystemMessages(userId, page, size);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取系统消息失败", e);
            return Result.error("获取系统消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 转发消息
     */
    @PostMapping("/forward")
    public Result<Message> forwardMessage(@RequestBody Map<String, Object> request,
                                         HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Long messageId = Long.valueOf(request.get("messageId").toString());
            Long receiverId = Long.valueOf(request.get("receiverId").toString());
            
            Message message = messageService.forwardMessage(messageId, userId, receiverId);
            return Result.success(message);
        } catch (Exception e) {
            log.error("转发消息失败", e);
            return Result.error("转发消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取消息统计
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getMessageStatistics(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Map<String, Object> statistics = messageService.getMessageStatistics(userId);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取消息统计失败", e);
            return Result.error("获取消息统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取消息详情
     */
    @GetMapping("/{messageId}")
    public Result<Message> getMessageById(@PathVariable Long messageId,
                                         HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            Message message = messageService.getMessageById(messageId, userId);
            if (message == null) {
                return Result.error("消息不存在或无权限访问");
            }
            return Result.success(message);
        } catch (Exception e) {
            log.error("获取消息详情失败", e);
            return Result.error("获取消息详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 从JWT令牌中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        return jwtUtil.getUserIdFromToken(token);
    }
}